package com.learn.multi_thread.A_BaseThread.C_ReentrantLock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TicketThreadForRunnableAboutLock implements Runnable {
//    static int ticket = 0; // 不需要了，因为Thread会创建多个，而Runnable只会创建一个
    int ticket = 0;

//    static final Object lockObject = new Object();  同理不需要单独声明一个锁对象
    Lock lock = new ReentrantLock();

    /**
     *  同步方法的创建
     *  1. 循环
     *  2. 同步
     *  3. 判断共享数据是否到了末尾，如果到了则么办？
     *                        ，如果没有到怎么办？
     */
    @Override
    public void run() {
        while (true) {
            lock.lock();
//            synchronized (TicketThreadForRunnableAboutLock.class) {
                if (ticket == 100) {
                    break;
                } else {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(
                            Thread.currentThread().getName() + "正在卖第" + (++ticket) + "张票"
                    );
                }
//            }
            lock.unlock();
        }
    }

}
